package util

import (
	"bytes"
	"compress/gzip"
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io/ioutil"
)

// 获取字符串的MD5值
func MD5(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	return hex.EncodeToString(h.Sum(nil))
}
// gzip压缩
func GzipEncode(s string) (string,error) {
	var	buffer bytes.Buffer
	writer := gzip.NewWriter(&buffer)
	_, err := writer.Write([]byte(s))
	if err != nil {
		writer.Close()
		return "", fmt.Errorf("压缩失败，err: %s",err)
	}
	err = writer.Close()
	if err != nil {
		return "", fmt.Errorf("关闭压缩流失败，err: %s",err)
	}
	return string(buffer.Bytes()),nil
}


// 解压GZIP数据
func GzipDecode(s string) (string, error) {

	reader, err := gzip.NewReader(bytes.NewReader([]byte(s)))
	if err != nil {
		return "", fmt.Errorf("gzip解压失败，err: %s", err)
	}
	defer reader.Close()
	dataBytes, err := ioutil.ReadAll(reader)
	if err != nil {
		return "", fmt.Errorf("从解压后的Reader中读取为[]byte失败，err: %s", err)
	}
	return string(dataBytes),nil
}


// 解压GZIP数据
func GzipDecodeBytes(b []byte) ([]byte, error) {

	reader, err := gzip.NewReader(bytes.NewReader(b))
	if err != nil {
		return []byte{}, fmt.Errorf("gzip解压失败，err: %s", err)
	}
	defer reader.Close()
	dataBytes, err := ioutil.ReadAll(reader)
	if err != nil {
		return []byte{}, fmt.Errorf("从解压后的Reader中读取为[]byte失败，err: %s", err)
	}
	return dataBytes,nil
}
